import traceback
from datetime import datetime
from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QScrollArea, 
                               QLabel, QLineEdit, QPushButton, QTextEdit, 
                               QDateEdit, QCheckBox, QFrame)
from PySide6.QtCore import Qt, QDate, QThread, Signal
from PySide6.QtGui import QTextCursor
from core.plugin_base import PluginBase


class WorkflowThread(QThread):
    """工作流程线程，用于执行后台任务"""
    log_signal = Signal(str)
    finished_signal = Signal(str)
    
    def __init__(self, folder_name, start_date, end_date, unread_only):
        super().__init__()
        self.folder_name = folder_name
        self.start_date = start_date
        self.end_date = end_date
        self.unread_only = unread_only
    
    def run(self):
        """执行工作流程"""
        try:
            self.log_signal.emit("[📧] 🚀 开始查询 PMD 邮件...")
            
            # TODO: 实现 Outlook 邮件查询逻辑
            self._query_outlook_emails()
            
            # TODO: 实现邮件筛选逻辑
            self._filter_emails_by_date()
            
            # TODO: 实现 BATCH 信息提取逻辑
            batch_info = self._extract_batch_info()
            
            # TODO: 实现 GCP 数据库查询逻辑
            sla_data = self._query_gcp_database(batch_info)
            
            # TODO: 实现 Excel 报告生成逻辑
            report_path = self._generate_excel_report(batch_info, sla_data)
            
            self.finished_signal.emit(report_path)
            
        except Exception as e:
            error_msg = f"[❌] 工作流程执行失败: {e} - {traceback.format_exc()}"
            self.log_signal.emit(error_msg)
    
    def _query_outlook_emails(self):
        """查询 Outlook 邮件"""
        # TODO: 实现 Outlook 邮件查询
        # 1. 连接到 Outlook
        # 2. 访问指定文件夹
        # 3. 获取所有邮件
        self.log_signal.emit(f"[📧] 正在查询文件夹: {self.folder_name}")
        self.log_signal.emit("[📧] TODO: 实现 Outlook 邮件查询逻辑")
    
    def _filter_emails_by_date(self):
        """按日期筛选邮件"""
        # TODO: 实现邮件日期筛选
        # 1. 筛选指定日期范围内的邮件
        # 2. 如果启用了 unread_only，只保留未读邮件
        self.log_signal.emit(f"[📅] 筛选日期范围: {self.start_date.toString('yyyy-MM-dd')} 到 {self.end_date.toString('yyyy-MM-dd')}")
        if self.unread_only:
            self.log_signal.emit("[📧] 只筛选未读邮件")
        self.log_signal.emit("[📅] TODO: 实现邮件日期筛选逻辑")
    
    def _extract_batch_info(self):
        """提取 BATCH 信息"""
        # TODO: 实现 BATCH 信息提取
        # 1. 解析邮件内容
        # 2. 提取 BATCH 相关信息
        # 3. 汇总成 DataFrame
        self.log_signal.emit("[📊] 正在提取 BATCH 信息...")
        self.log_signal.emit("[📊] TODO: 实现 BATCH 信息提取逻辑")
        return {}  # Mock 返回值
    
    def _query_gcp_database(self, batch_info):
        """查询 GCP 数据库"""
        # TODO: 实现 GCP 数据库查询
        # 1. 根据 BATCH 信息生成 SQL 语句
        # 2. 连接 GCP BigQuery
        # 3. 执行查询获取 SLA 信息
        self.log_signal.emit("[🔍] 正在查询 GCP 数据库...")
        self.log_signal.emit("[🔍] TODO: 实现 GCP 数据库查询逻辑")
        return {}  # Mock 返回值
    
    def _generate_excel_report(self, batch_info, sla_data):
        """生成 Excel 报告"""
        # TODO: 实现 Excel 报告生成
        # 1. 合并 BATCH 信息和 SLA 数据
        # 2. 创建 DataFrame
        # 3. 导出到 Excel 文件
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        report_path = f"reports/PMD_Monthly_Report_{timestamp}.xlsx"
        self.log_signal.emit(f"[📄] 正在生成报告: {report_path}")
        self.log_signal.emit("[📄] TODO: 实现 Excel 报告生成逻辑")
        return report_path


class Plugin(PluginBase):
    """Monthly PMD Helper 插件"""
    
    NAME = "monthly_pmd_helper"
    DISPLAY_NAME = "Monthly PMD Helper"
    DESCRIPTION = "Thanks to Vicky's PMD configuration, making the tedious monthly batch work semi-automated"
    VERSION = "1.0.0"
    AUTHOR = "Tearsyu"
    
    def __init__(self, app=None):
        super().__init__(app)
        self.workflow_thread = None
    
    def initialize(self) -> bool:
        """初始化插件"""
        try:
            self.log_info("[🔌] 🚀 Monthly PMD Helper 插件初始化完成")
            return True
        except Exception as e:
            self.log_error(f"[🔌] ❌ 插件初始化失败: {e} - {traceback.format_exc()}")
            return False
    
    def create_widget(self) -> QWidget:
        """创建插件界面组件"""
        # 创建主容器
        main_widget = QWidget()
        main_layout = QVBoxLayout(main_widget)
        
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        
        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_layout = QVBoxLayout(scroll_content)
        scroll_layout.setSpacing(15)
        scroll_layout.setContentsMargins(20, 20, 20, 20)
        
        # 1. PMD 文件夹输入框
        folder_frame = self._create_folder_input_section()
        scroll_layout.addWidget(folder_frame)
        
        # 2. 日期选择框
        date_frame = self._create_date_selection_section()
        scroll_layout.addWidget(date_frame)
        
        # 3. 未读邮件复选框
        unread_frame = self._create_unread_checkbox_section()
        scroll_layout.addWidget(unread_frame)
        
        # 4. 查询按钮
        query_frame = self._create_query_button_section()
        scroll_layout.addWidget(query_frame)
        
        # 5. 日志文本框
        log_frame = self._create_log_text_section()
        scroll_layout.addWidget(log_frame)
        
        # 设置滚动区域内容
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)
        
        return main_widget
    
    def _create_folder_input_section(self) -> QFrame:
        """创建文件夹输入区域"""
        frame = QFrame()
        frame.setFrameStyle(QFrame.Box)
        layout = QVBoxLayout(frame)
        
        # 标题
        title_label = QLabel(self.tr("plugin.monthly_pmd_helper.folder_title"))
        title_label.setStyleSheet("font-weight: bold; font-size: 14px; color: #2c3e50;")
        layout.addWidget(title_label)
        
        # 输入框
        self.folder_input = QLineEdit()
        self.folder_input.setPlaceholderText(self.tr("plugin.monthly_pmd_helper.folder_placeholder"))
        self.folder_input.setText(self.get_setting("pmd_folder_name", "PMD"))
        self.folder_input.textChanged.connect(self._on_folder_changed)
        self.folder_input.setStyleSheet("""
            QLineEdit {
                padding: 8px;
                border: 2px solid #bdc3c7;
                border-radius: 5px;
                font-size: 12px;
            }
            QLineEdit:focus {
                border-color: #3498db;
            }
        """)
        layout.addWidget(self.folder_input)
        
        return frame
    
    def _create_date_selection_section(self) -> QFrame:
        """创建日期选择区域"""
        frame = QFrame()
        frame.setFrameStyle(QFrame.Box)
        layout = QVBoxLayout(frame)
        
        # 标题
        title_label = QLabel(self.tr("plugin.monthly_pmd_helper.date_title"))
        title_label.setStyleSheet("font-weight: bold; font-size: 14px; color: #2c3e50;")
        layout.addWidget(title_label)
        
        # 日期选择器容器
        date_container = QHBoxLayout()
        
        # 开始日期
        start_label = QLabel(self.tr("plugin.monthly_pmd_helper.start_date"))
        self.start_date_edit = QDateEdit()
        self.start_date_edit.setDate(QDate.currentDate())
        self.start_date_edit.setCalendarPopup(True)
        self.start_date_edit.setStyleSheet("""
            QDateEdit {
                padding: 8px;
                border: 2px solid #bdc3c7;
                border-radius: 5px;
                font-size: 12px;
            }
        """)
        
        # 结束日期
        end_label = QLabel(self.tr("plugin.monthly_pmd_helper.end_date"))
        self.end_date_edit = QDateEdit()
        self.end_date_edit.setDate(QDate.currentDate())
        self.end_date_edit.setCalendarPopup(True)
        self.end_date_edit.setStyleSheet("""
            QDateEdit {
                padding: 8px;
                border: 2px solid #bdc3c7;
                border-radius: 5px;
                font-size: 12px;
            }
        """)
        
        date_container.addWidget(start_label)
        date_container.addWidget(self.start_date_edit)
        date_container.addWidget(end_label)
        date_container.addWidget(self.end_date_edit)
        
        layout.addLayout(date_container)
        
        return frame
    
    def _create_unread_checkbox_section(self) -> QFrame:
        """创建未读邮件复选框区域"""
        frame = QFrame()
        frame.setFrameStyle(QFrame.Box)
        layout = QVBoxLayout(frame)
        
        # 复选框
        self.unread_checkbox = QCheckBox(self.tr("plugin.monthly_pmd_helper.unread_only"))
        self.unread_checkbox.setChecked(self.get_setting("unread_only", True))
        self.unread_checkbox.setStyleSheet("""
            QCheckBox {
                font-size: 12px;
                color: #2c3e50;
            }
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
            }
        """)
        layout.addWidget(self.unread_checkbox)
        
        return frame
    
    def _create_query_button_section(self) -> QFrame:
        """创建查询按钮区域"""
        frame = QFrame()
        frame.setFrameStyle(QFrame.Box)
        layout = QVBoxLayout(frame)
        
        # 查询按钮
        self.query_button = QPushButton(self.tr("plugin.monthly_pmd_helper.query_button"))
        self.query_button.clicked.connect(self._on_query_clicked)
        self.query_button.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 12px 24px;
                font-size: 14px;
                font-weight: bold;
                border-radius: 6px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #21618c;
            }
            QPushButton:disabled {
                background-color: #bdc3c7;
                color: #7f8c8d;
            }
        """)
        layout.addWidget(self.query_button)
        
        return frame
    
    def _create_log_text_section(self) -> QFrame:
        """创建日志文本区域"""
        frame = QFrame()
        frame.setFrameStyle(QFrame.Box)
        layout = QVBoxLayout(frame)
        
        # 标题
        title_label = QLabel(self.tr("plugin.monthly_pmd_helper.log_title"))
        title_label.setStyleSheet("font-weight: bold; font-size: 14px; color: #2c3e50;")
        layout.addWidget(title_label)
        
        # 日志文本框
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setMinimumHeight(200)
        self.log_text.setStyleSheet("""
            QTextEdit {
                background-color: #2c3e50;
                color: #ecf0f1;
                border: 2px solid #34495e;
                border-radius: 5px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 11px;
                padding: 10px;
            }
        """)
        layout.addWidget(self.log_text)
        
        return frame
    
    def _on_folder_changed(self, text: str):
        """文件夹名称改变时的回调"""
        self.set_setting("pmd_folder_name", text)
        self.log_debug(f"[📁] PMD 文件夹名称已更新: {text}")
    
    def _on_unread_changed(self, checked):
        """未读选项改变时更新内部状态"""
        self.unread_only = checked
    
    def _on_query_clicked(self):
        """查询按钮点击事件"""
        try:
            # 验证输入
            folder_name = self.folder_input.text().strip()
            if not folder_name:
                self.log_warning("[⚠️] 请输入 PMD 文件夹名称")
                self.show_status_message(self.tr("plugin.monthly_pmd_helper.folder_required"))
                return
            
            # 禁用按钮防止重复点击
            self.query_button.setEnabled(False)
            self.query_button.setText(self.tr("plugin.monthly_pmd_helper.querying"))
            
            # 清空日志
            self.log_text.clear()
            
            # 获取参数
            start_date = self.start_date_edit.date()
            end_date = self.end_date_edit.date()
            unread_only = self.unread_checkbox.isChecked()
            
            # 保存设置
            self.set_setting("unread_only", unread_only)
            
            # 启动工作流程线程
            self.workflow_thread = WorkflowThread(folder_name, start_date, end_date, unread_only)
            self.workflow_thread.log_signal.connect(self._append_log)
            self.workflow_thread.finished_signal.connect(self._on_workflow_finished)
            self.workflow_thread.start()
            
            self.log_info(f"[🚀] 开始查询 PMD 邮件，文件夹: {folder_name}")
            
        except Exception as e:
            self.log_error(f"[❌] 查询启动失败: {e} - {traceback.format_exc()}")
            self._reset_query_button()
    
    def _append_log(self, message: str):
        """添加日志消息"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        formatted_message = f"[{timestamp}] {message}"
        self.log_text.append(formatted_message)
        
        # 自动滚动到底部
        cursor = self.log_text.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.log_text.setTextCursor(cursor)
    
    def _on_workflow_finished(self, report_path: str):
        """工作流程完成回调"""
        self._append_log(f"[✅] 查询完成！报告已生成: {report_path}")
        self.show_status_message(self.tr("plugin.monthly_pmd_helper.query_completed"))
        self._reset_query_button()
    
    def _reset_query_button(self):
        """重置查询按钮状态"""
        self.query_button.setEnabled(True)
        self.query_button.setText(self.tr("plugin.monthly_pmd_helper.query_button"))
    
    def cleanup(self) -> None:
        """清理插件资源"""
        try:
            # 停止工作流程线程
            if self.workflow_thread and self.workflow_thread.isRunning():
                self.workflow_thread.quit()
                self.workflow_thread.wait(3000)  # 等待最多3秒
                self.workflow_thread = None
            
            self.log_info("[🔌] 🧹 Monthly PMD Helper 插件清理完成")
            
        except Exception as e:
            self.log_error(f"[🔌] ❌ 插件清理失败: {e} - {traceback.format_exc()}")